<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数智作业后台管理系统 - 登录</title>
    <link rel="icon" href="/assets/ico/7favicon.png" type="image/png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 2px;
            transition: all 0.3s ease;
        }
        .gradient-bg {
            background: linear-gradient(90deg, #4f46e5 0%, #3b82f6 100%);
        }
        .login-card {
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(209, 213, 219, 0.3);
        }
        .input-group {
            position: relative;
        }
        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6b7280;
        }
        body {
            background-image: url('https://source.unsplash.com/random/1920x1080/?gradient');
            background-size: cover;
            background-position: center;
        }
        .animate-fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gray-100 flex justify-center items-center h-screen">
<div class="bg-white bg-opacity-95 p-10 rounded-xl login-card w-full max-w-md animate-fade-in">
    <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-transparent bg-clip-text gradient-bg inline-block">数智作业后台管理系统</h1>
        <p class="text-gray-500 mt-2">请登录以继续访问</p>
    </div>
    
    <form id="loginForm" class="space-y-6">
        <div class="form-group">
            <label for="account" class="block text-gray-700 font-medium mb-2">账号</label>
            <input type="text" id="account" name="account" 
                class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200" 
                placeholder="请输入用户名或手机号" required>
        </div>
        
        <div>
            <label for="password" class="block text-gray-700 font-medium mb-2">密码</label>
            <div class="input-group">
                <input type="password" id="password" name="password" 
                    class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200" 
                    placeholder="请输入密码" required>
                <span class="toggle-password" id="togglePassword">
                    <i class="fas fa-eye-slash"></i>
                </span>
            </div>
        </div>
        
        <div class="flex items-center mb-4">
            <input type="checkbox" id="rememberMe" class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
            <label for="rememberMe" class="ml-2 text-sm font-medium text-gray-600">记住密码</label>
        </div>
        
        <button type="submit" 
            class="w-full py-3 px-4 bg-gradient-to-r from-blue-600 to-indigo-600 text-white font-medium rounded-lg hover:from-blue-700 hover:to-indigo-700 transition duration-300 shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
            登录
        </button>
        
        <!-- 添加注册和忘记密码按钮 -->
        <div class="flex justify-between mt-3">
            <a href="register.html" class="text-sm text-blue-600 hover:text-blue-800 transition-colors">还没有账号？点击注册</a>
            <a href="forgot-password.html" class="text-sm text-blue-600 hover:text-blue-800 transition-colors">忘记密码？</a>
        </div>
    </form>
    
    <!-- 添加更美观的错误提示框 -->
    <div id="errorMsg" class="hidden">
        <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-md mb-4 animate-fade-in">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-red-700" id="errorMsgText">用户名或密码错误</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 检查URL参数是否包含error，如果有则显示错误消息
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('error')) {
        const errorMsg = document.getElementById('errorMsg');
        const errorMsgText = document.getElementById('errorMsgText');
        
        // 设置不同的错误消息
        if (urlParams.get('error') === 'expired') {
            errorMsgText.innerHTML = '您的登录已过期，请重新登录';
        } else if (urlParams.get('error') === 'elsewhere') {
            errorMsgText.innerHTML = '您的账号已在其他设备登录';
        } else if (urlParams.get('error') === 'invalid') {
            errorMsgText.innerHTML = '您的登录状态已失效，请重新登录';
        } else if (urlParams.get('error') === 'refresh_failed') {
            errorMsgText.innerHTML = '会话刷新失败，请重新登录';
        } else if (urlParams.get('error') === 'session_refreshed') {
            errorMsgText.innerHTML = '会话已被刷新，请重新登录';
        } else {
            errorMsgText.innerHTML = '账号或密码错误';
        }
        
        errorMsg.classList.remove('hidden');
    }
    
    // 检查是否已经登录，如果已登录则直接跳转到首页
    if (sessionStorage.getItem('isLoggedIn') === 'true' && sessionStorage.getItem('jwtToken')) {
        window.location.href = 'index.html';
    }
    
    // 检查是否有错误原因，如果有则显示
    const loginErrorReason = sessionStorage.getItem('loginErrorReason');
    if (loginErrorReason) {
        const errorMsg = document.getElementById('errorMsg');
        const errorMsgText = document.getElementById('errorMsgText');
        
        // 设置消息内容
        errorMsgText.innerHTML = loginErrorReason;
        errorMsg.classList.remove('hidden');
        
        // 显示后清除，避免刷新页面仍然显示
        sessionStorage.removeItem('loginErrorReason');
    }
    
    const loginForm = document.getElementById('loginForm');
    const errorMsg = document.getElementById('errorMsg');
    const passwordInput = document.getElementById('password');
    const togglePassword = document.getElementById('togglePassword');
    const accountInput = document.getElementById('account');
    const rememberMeCheckbox = document.getElementById('rememberMe');
    
    // 检查是否有保存的登录信息
    window.addEventListener('DOMContentLoaded', function() {
        const savedAccount = localStorage.getItem('rememberedAccount');
        const savedPassword = localStorage.getItem('rememberedPassword');
        const rememberMe = localStorage.getItem('rememberMe');
        
        if (savedAccount && savedPassword && rememberMe === 'true') {
            accountInput.value = savedAccount;
            passwordInput.value = savedPassword;
            rememberMeCheckbox.checked = true;
        }
    });
    
    // 密码可见性切换
    togglePassword.addEventListener('click', function() {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        
        // 切换图标
        togglePassword.querySelector('i').classList.toggle('fa-eye');
        togglePassword.querySelector('i').classList.toggle('fa-eye-slash');
    });
    
    // 表单验证
    function validateForm() {
        const account = accountInput.value.trim();
        const password = passwordInput.value.trim();
        
        // 验证账号
        if (!account) {
            errorMsgText.innerHTML = '请输入用户名或手机号';
            errorMsg.classList.remove('hidden');
            return false;
        }
        
        // 验证密码
        if (password.length < 6) {
            errorMsgText.innerHTML = '密码长度不能少于6个字符';
            errorMsg.classList.remove('hidden');
            return false;
        }
        
        return true;
    }
    
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // 隐藏之前的错误消息
        errorMsg.classList.add('hidden');
        
        // 表单验证
        if (!validateForm()) {
            return;
        }
        
        const account = accountInput.value.trim();
        const password = passwordInput.value.trim();
        const rememberMe = rememberMeCheckbox.checked;
        
        // 记住密码功能
        if (rememberMe) {
            localStorage.setItem('rememberedAccount', account);
            localStorage.setItem('rememberedPassword', password);
            localStorage.setItem('rememberMe', 'true');
        } else {
            localStorage.removeItem('rememberedAccount');
            localStorage.removeItem('rememberedPassword');
            localStorage.removeItem('rememberMe');
        }
        
        const submitButton = loginForm.querySelector('button[type="submit"]');
        submitButton.innerHTML = '<i class="fas fa-circle-notch fa-spin mr-2"></i>登录中...';
        submitButton.disabled = true;

        try {
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: `username=${encodeURIComponent(account)}&password=${encodeURIComponent(password)}`
            });

            const data = await response.json();
            
            if (response.ok && data.success) {
                console.log('登录成功，获取到用户信息和令牌');
                
                // 存储登录状态和用户信息
                sessionStorage.setItem('isLoggedIn', 'true');
                sessionStorage.setItem('jwtToken', data.token);
                sessionStorage.setItem('userFullName', data.fullName || data.username);
                sessionStorage.setItem('userRole', data.role);
                
                // 跳转到首页
                window.location.href = 'index.html';
            } else {
                // 处理错误响应
                errorMsgText.innerHTML = data.message || '账号或密码错误';
                errorMsg.classList.remove('hidden');
                submitButton.innerHTML = '登录';
                submitButton.disabled = false;
            }
        } catch (error) {
            console.error('登录请求出错:', error);
            errorMsgText.innerHTML = '登录请求失败，请稍后再试';
            errorMsg.classList.remove('hidden');
            submitButton.innerHTML = '登录';
            submitButton.disabled = false;
        }
    });
</script>
</body>
</html>